﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlueLotus7.ArchiveSystem.Common.Contracts.Sina.Weibo;
using System.Xml;

namespace BlueLotus7.ArchiveSystem.SinaContentApi.Weibo
{
    partial class ContentAnalyzer
    {
        public static List<WeiboArticle> TranslateWeiboArticles(string htmlContent)
        {
            List<WeiboArticle> articles = new List<WeiboArticle>();

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                htmlContent = CleanHtmlContent(htmlContent);
            }

            return articles;
        }

        private static WeiboArticle TranslateWeiboArticleSummaryHtml(string htmlContent)
        {
            WeiboArticle article = null;

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                article = new WeiboArticle();


            }

            return article;
        }

        private static WeiboArticle TranslateWeiboArticleDetailHtml(string htmlContent)
        {
            WeiboArticle article = null;

            if (!string.IsNullOrWhiteSpace(htmlContent))
            {
                article = new WeiboArticle();


            }

            return article;
        }

        //<div class="c" id="C_3420259237655828">
        //<a href="/13861201?vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">鱼丸一世</a>:<span
        //    class="ctt">回复<a href="/n/%E6%9C%AB%E6%9C%88de%E9%B1%BC?vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">@末月de鱼</a>:。。。。。下作呸！</span>&nbsp;<span
        //        class="cc"><a href="/comments/reply/y8uUXxOS5/3420259237655828?rl=1&amp;vt=4&amp;gsid=3_5bc353f8e36c2c83509a65bbeb0af98e0a435261">回复</a></span>&nbsp;<span
        //            class="ct">03月05日 16:40&nbsp;来自新浪微博</span></div>
        private static WeiboArticle TranslateWeiboArticleCommentHtml(XmlNode divNode, Guid articleGuid, List<WeiboArticle> commentsClain, WeiboContentRetriever retirever)
        {
            const string errorInvalidCommentId = "Invalid article comment ID.";
            const string errorInvalidCommentOwnerId = "Invalid article comment owner ID.";
            const string errorInvalidCommentOwner = "Comment owner not found for {0}.";
            const string errorInvalidPreviousCommentOwner = "Invalid article previous comment owner ID.";
            const string errorInvalidTimeAgentSign = "Invalid time and agent signs.";

            WeiboArticle comment = null;
            if (divNode != null)
            {
                //Comment ID
                string commentId = GetXmlAttributeValue(divNode, tag_id);
                if (string.IsNullOrWhiteSpace(commentId) || commentId.StartsWith("C_"))
                {
                    throw new Exception(errorInvalidCommentId);
                }

                commentId = commentId.Substring(2, commentId.Length - 2);
                comment = new WeiboArticle();
                comment.ContentType = WeiboArticle.WeiboContentType.WeiboComments;

                //Owner
                string ownerLink = GetXmlAttributeValue(divNode.ChildNodes[0], tag_href);
                if (string.IsNullOrWhiteSpace(ownerLink))
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                int index = ownerLink.IndexOf('?');
                if (index < 0)
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                string ownerIdentity = ownerLink.Trim('/').Substring(0, index);
                long ownerUid = 0;
                if (string.IsNullOrWhiteSpace(ownerIdentity) || long.TryParse(ownerIdentity, out ownerUid))
                {
                    throw new Exception(errorInvalidCommentOwnerId);
                }

                WeiboUser user = retirever.RetrieveWeiboUserGuidByThirdPartyIdentity(ownerUid);
                if (user == null)
                {
                    throw new Exception(string.Format(errorInvalidCommentOwner, ownerIdentity));
                }
                comment.Owner = user.Key;

                //Previous Comment Owner
                XmlNode commentToTargetNode = divNode.SelectSingleNode("descendant::span[@class='" + class_CommentToTarget + "']");
                XmlNode previousCommentUserNode = commentToTargetNode.SelectSingleNode("descendant::a");
                if (previousCommentUserNode == null)
                {
                    throw new Exception(errorInvalidPreviousCommentOwner);
                }

                ownerLink = GetXmlAttributeValue(previousCommentUserNode, tag_href);
                if (string.IsNullOrWhiteSpace(ownerLink))
                {
                    throw new Exception(errorInvalidPreviousCommentOwner);
                }

                user = retirever.RetrieveWeiboUserByUrl(ownerLink);
                if (user == null)
                {
                    throw new Exception(errorInvalidPreviousCommentOwner);
                }
                WeiboArticle previousComment = FindWeiboCommentByLastOwner(commentsClain, user.Key);
                if (previousComment != null)
                {
                    comment.CommentFor = previousComment.Key;
                }
                commentToTargetNode.RemoveChild(previousCommentUserNode);
                string commentContent = commentToTargetNode.InnerText.Substring(content_replyConstString.Length);
                comment.TextContent = commentContent;

                XmlNode timeAgentNode = divNode.SelectSingleNode("descendant::span[@class='" + class_CommentTime + "']");
                if (timeAgentNode == null)
                {
                    throw new Exception(errorInvalidTimeAgentSign);
                }

                string[] agentParts = timeAgentNode.InnerText.Split(new string[] { html_space }, StringSplitOptions.RemoveEmptyEntries);
                comment.Agent = agentParts[1].Substring(content_fromConstString.Length);
                comment.CreatedStamp = Convert.ToDateTime(agentParts[0]);
            }
            return comment;
        }


        private static WeiboArticle FindWeiboCommentByLastOwner(List<WeiboArticle> commentsClain, Guid ownerGuid)
        {
            WeiboArticle result = null;
            for (int i = commentsClain.Count - 1; i >= 0; i--)
            {
                if (commentsClain[i].Owner == ownerGuid)
                {
                    result = commentsClain[i];
                    break;
                }
            }

            return result;
        }

    }
}
